from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import file_upload
import csv
from django.views.decorators.http import require_GET, require_http_methods, require_POST
from subprocess import PIPE, Popen


def get_csv(request, id, name):
    print(id, name)
    response = HttpResponse(content_type="text/csv")
    response['Content-Disposition'] = 'attachment;filename="somefile.csv"'
    write = csv.writer(response)
    write.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    write.writerow(['Second row', 'A', 'B', 'C', '"testing"', "Here's  a quote"])
    return response


def test(request):
    response = "1423423"
    if response is None:
        return HttpResponse("NOT name ")
    return HttpResponse(response)


def get_file(request, id):
    # f=open('/tmp/[MySQL]MySQL 5.1参考手册.chm','rb')
    # response=HttpResponse(f,content_type='application/chm')
    # response['Content-Disposition']='attachment;filename="test.chm"'
    # f.close()
    filename = request.GET.get('filename', None)
    if filename is None:
        return redirect('/1/file/get_csv')
        # return  redirect(test)
    return render(request, 'getfile.html')


def pub_file(request, id):
    if request.method == 'POST':
        upload_file = request.FILES.get('file', None)
        if upload_file is None:
            return HttpResponse('No  file get')
        else:
            with  open('/tmp/{}'.format(upload_file.name), 'wb')  as  f:
                f.write(upload_file.read())
            F = file_upload()
            F.name = upload_file.name
            F.path = '/tmp/{}'.format(upload_file.name)
            F.file_size = upload_file.size
            try:
                F.save()
            except  Exception  as e:
                print(e)
            return HttpResponse('文件:{}上传成功'.format(upload_file.name))
    else:
        return render(request, 'upload.html')
